package com.example.train.common.config.security.handler;

import cn.hutool.json.JSONUtil;
import com.example.train.common.base.model.ResponseBase;
import com.example.train.common.constant.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtAuthFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setCharacterEncoding(SysConstant.CHARACTER_ENCODING);
        response.setContentType(SysConstant.CONTENT_TYPE);
        response.getWriter().println(JSONUtil.parse(ResponseBase.validateFailed(e.getMessage())));
        response.getWriter().flush();
    }
}
